package com.golden.procedure.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.golden.procedure.domain.QueryRequest;
import com.golden.procedure.domain.SingleRequest;
import com.golden.procedure.domain.WorkCommentDO;
import com.golden.procedure.domain.WorkCommissionDO;
import com.golden.procedure.domain.WorkOrderDO;
import com.golden.procedure.entity.WorkOrder;
import com.golden.procedure.query.WorkCommissionQueryDO;
import com.golden.procedure.query.WorkOrderQueryDO;
import com.golden.procedure.result.PageResponse;
import com.golden.procedure.result.ResultDO;
import com.golden.procedure.result.SingleResponse;
import com.golden.procedure.service.IWorkCommentService;
import com.golden.procedure.service.IWorkCommissionService;
import com.golden.procedure.service.IWorkOrderService;
import com.golden.procedure.util.BonConstant;
import com.golden.procedure.util.EncryptedUtil;
import com.golden.procedure.util.HttpStatus;
import com.golden.procedure.util.TaskDefKey;
import com.google.gson.Gson;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 工单信息管理接口 <b>Description:</b><br>
 * 
 * @author Reading.Reagan</a>
 * @version 1.0
 * @Note <b>ProjectName:</b> procedure <br>
 *       <b>PackageName:</b> com.golden.procedure.controller <br>
 *       <b>ClassName:</b> WorkOrderController <br>
 *       <b>Date:</b> 2018年10月23日 上午10:18:28
 */
@RestController
@RequestMapping(value = "/api/workOrder")
public class WorkOrderController extends BaseController {

	@Autowired
	IWorkOrderService workOrderService;
	@Autowired
	IWorkCommentService workCommentService;
	@Autowired
	IWorkCommissionService workCommissionService;

	public static String encodeObject(SingleResponse<WorkOrderDO> response, String encryptType) {
		Gson gson = new Gson();
		String jsonData = gson.toJson(response);
		try {
			return EncryptedUtil.encrypt(jsonData, encryptType);
		} catch (Exception e) {
			e.printStackTrace();
			return SYS_ERROR;
		}
	}

	public static String encodeWorkOrderPage(PageResponse<WorkOrderDO> response, String encryptType) {
		Gson gson = new Gson();
		String jsonData = gson.toJson(response);
		try {
			return EncryptedUtil.encrypt(jsonData, encryptType);
		} catch (Exception e) {
			e.printStackTrace();
			return SYS_ERROR;
		}
	}

	public static String encodeCommentPage(PageResponse<WorkCommentDO> response, String encryptType) {
		Gson gson = new Gson();
		String jsonData = gson.toJson(response);
		try {
			return EncryptedUtil.encrypt(jsonData, encryptType);
		} catch (Exception e) {
			e.printStackTrace();
			return SYS_ERROR;
		}
	}

	public static String encodeCommission(SingleResponse<WorkCommissionDO> response, String encryptType) {
		Gson gson = new Gson();
		String jsonData = gson.toJson(response);
		try {
			return EncryptedUtil.encrypt(jsonData, encryptType);
		} catch (Exception e) {
			e.printStackTrace();
			return SYS_ERROR;
		}
	}

	public static String encodeCommissionPage(PageResponse<WorkCommissionDO> response, String encryptType) {
		Gson gson = new Gson();
		String jsonData = gson.toJson(response);
		try {
			return EncryptedUtil.encrypt(jsonData, encryptType);
		} catch (Exception e) {
			e.printStackTrace();
			return SYS_ERROR;
		}
	}

	@ApiOperation(value = "查询工单", notes = "查询工单（预约拍摄）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "isFirstBooking", value = "新预约,:0--未选中 1--选中", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "isChangeDate", value = "改期订单:0--未选中 1--选中", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "isRebook", value = "重拍/补拍:0--未选中 1--选中", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "type", value = "订单类型(免费、新生儿等)", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "nameOrTel", value = "客户姓名或者手机", required = false, dataType = "String") })
	@RequestMapping(value = "/query.json", method = RequestMethod.POST)
	public String query(@RequestBody QueryRequest<WorkOrderQueryDO> request) {

		// {"data":
		// {"isFirstBooking":1,"isChangeDate":1,"isRebook":1,"type":0,"nameOrTel":""},"version":1,"token":"W57m+iUG3/D+y/KY6V8ktuboDcz0nFIw62hRSUwHmUA="}
		WorkOrderQueryDO query = request.getData();
		if (query.getPageRows() > 0) {
			query.setPage(true);
		}

		// 1. 根据条件设置查询条件
		List<Integer> isRePhotograph = new ArrayList<Integer>();
		List<Integer> isReshot = new ArrayList<Integer>();
		List<Integer> isChangeDate = new ArrayList<Integer>();
		List<Integer> orderStatus = new ArrayList<Integer>();
		if (query.getIsFirstBooking() == 1) {
			// 新预约,:0--未选中 1--选中
			isRePhotograph.add(BonConstant.STATUS_FALSE); // 非重拍
			isReshot.add(BonConstant.STATUS_FALSE);	// 非补拍
			isChangeDate.add(BonConstant.STATUS_FALSE);	// 非改期
			orderStatus.add(BonConstant.ORDER_STATUS_NORMAL);	// 订单状态:正常
		}
		if (query.getIsChangeDate() == 1) {
			// 改期订单:0--未选中 1--选中
			isChangeDate.add(BonConstant.STATUS_TRUE);	// 改期
			orderStatus.add(BonConstant.ORDER_STATUS_CHANGEDATE);	// 订单状态:改期
			orderStatus.add(BonConstant.ORDER_STATUS_CANCEL);	// 订单状态:取消
		}
		if (query.getIsRebook() == 1) {
			// 重拍/补拍:0--未选中 1--选中
			isRePhotograph.add(BonConstant.STATUS_TRUE);	// 重拍
			isReshot.add(BonConstant.STATUS_TRUE);	// 补拍
			orderStatus.add(BonConstant.ORDER_STATUS_REPHOTOGRAPH);	// 订单状态:重拍
			orderStatus.add(BonConstant.ORDER_STATUS_RESHOT);	// 订单状态:补拍
		}
		query.setRePhotographList(isRePhotograph);
		query.setReshotList(isReshot);
		query.setChangeDateList(isChangeDate);
		query.setOrderStatus(orderStatus);
		// 预约拍摄节点（待拍摄的工单）
		query.setTasks(Arrays.asList(new String[]{TaskDefKey.ORDER_SCHEDULE.getKey()}));
		// 工单服务状态： 进行中
		query.setStatus(BonConstant.WORKORDER_STATUS_GOING);

		PageResponse<WorkOrderDO> response = new PageResponse<WorkOrderDO>();
		ResultDO resultDO = workOrderService.query(query);
		if (resultDO.isSuccess()) {
			response.setStatus(HttpStatus.SUCCESS.getErrorCode());
			response.setVersion(1);
			response.setMsg(HttpStatus.SUCCESS.getMsg());
			response.setData((List<WorkOrderDO>) resultDO.getModel(ResultDO.FIRST_MODEL_KEY));
			if (query.isPage()) {
				response.setTotal((int) resultDO.getModel(ResultDO.SECOND_MODEL_KEY));
			}
		} else {
			// 查询失败
			response.setStatus(HttpStatus.SYSTEM_ERROR.getErrorCode());
			response.setVersion(1);
			response.setMsg(resultDO.getErrorMsg());
		}

		return encodeWorkOrderPage(response, PLANINTEXT);
	}

	@ApiOperation(value = "添加员工提成记录", notes = "添加员工提成记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "workOrderID", value = "工单id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "workerID", value = "工单服务成员id", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "commissionProj", value = "项目（字典）", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "commissionItem", value = "提成方式（字典）", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "commissionNum", value = "数值", required = true, dataType = "Integer") })
	@RequestMapping(value = "/addCommission.json", method = RequestMethod.POST)
	public String addCommission(@RequestBody SingleRequest<WorkCommissionDO> request) {

		WorkCommissionDO commissionDO = request.getData();

		commissionDO.setAuthorID(9);
		commissionDO.setAuthor("test");

		SingleResponse<WorkCommissionDO> response = new SingleResponse<WorkCommissionDO>();
		ResultDO resultDO = workCommissionService.add(commissionDO);
		if (resultDO.isSuccess()) {
			response.setStatus(HttpStatus.SUCCESS.getErrorCode());
			response.setVersion(0);
			response.setMsg(HttpStatus.SUCCESS.getMsg());
		} else {
			response.setStatus(HttpStatus.SYSTEM_ERROR.getErrorCode());
			response.setVersion(1);
			response.setMsg(resultDO.getErrorMsg());
		}
		return encodeCommission(response, PLANINTEXT);
	}

	@ApiOperation(value = "查询员工提成记录", notes = "查询员工提成记录")
	@ApiImplicitParam(name = "workOrderID", value = "工单id", required = true, dataType = "Integer")
	@RequestMapping(value = "/queryCommission.json", method = RequestMethod.POST)
	public String queryCommission(@RequestBody QueryRequest<WorkCommissionQueryDO> request) {

		WorkCommissionQueryDO queryDO = request.getData();

		PageResponse<WorkCommissionDO> response = new PageResponse<WorkCommissionDO>();
		ResultDO resultDO = workCommissionService.query(queryDO);
		if (resultDO.isSuccess()) {
			response.setStatus(HttpStatus.SUCCESS.getErrorCode());
			response.setVersion(0);
			response.setMsg(HttpStatus.SUCCESS.getMsg());
			response.setData((List<WorkCommissionDO>) resultDO.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(HttpStatus.SYSTEM_ERROR.getErrorCode());
			response.setVersion(1);
			response.setMsg(resultDO.getErrorMsg());
		}
		return encodeCommissionPage(response, PLANINTEXT);
	}

	@ApiOperation(value = "查询工单服务记录", notes = "查询工单服务记录")
	@ApiImplicitParam(name = "workOrderId", value = "上门组ID", required = true, dataType = "Integer")
	@RequestMapping(value = "/serviceRecord.json", method = RequestMethod.POST)
	public String queryServiceRecord(@RequestBody QueryRequest<WorkCommentDO> request) {

		WorkCommentDO domain = request.getData();
		PageResponse<WorkCommentDO> response = new PageResponse<WorkCommentDO>();
		ResultDO resultDO = workCommentService.queryByWorkOrderID(domain.getWorkOrderID());
		if (resultDO.isSuccess()) {
			response.setStatus(HttpStatus.SUCCESS.getErrorCode());
			response.setVersion(1);
			response.setMsg(HttpStatus.SUCCESS.getMsg());
			response.setData((List<WorkCommentDO>) resultDO.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			// 查询失败
			response.setStatus(HttpStatus.SYSTEM_ERROR.getErrorCode());
			response.setVersion(1);
			response.setMsg(resultDO.getErrorMsg());
		}

		return encodeCommentPage(response, PLANINTEXT);
	}

	@ApiOperation(value = "查询工单详情", notes = "查询工单详情")
	@ApiImplicitParam(name = "id", value = "工单id", required = true, dataType = "Integer")
	@RequestMapping(value = "/get.json", method = RequestMethod.POST)
	public String get(@RequestBody SingleRequest<WorkOrderDO> request) {

		WorkOrderDO domain = request.getData();
		SingleResponse<WorkOrderDO> response = new SingleResponse<WorkOrderDO>();
		ResultDO resultDO = workOrderService.get(domain.getId());
		if (resultDO.isSuccess()) {
			response.setStatus(HttpStatus.SUCCESS.getErrorCode());
			response.setVersion(1);
			response.setMsg(HttpStatus.SUCCESS.getMsg());
			response.setData((WorkOrderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			// 查询失败
			response.setStatus(HttpStatus.SYSTEM_ERROR.getErrorCode());
			response.setVersion(1);
			response.setMsg(resultDO.getErrorMsg());
		}

		return encodeObject(response, PLANINTEXT);
	}
	
	@ApiOperation(value = "创建工单（Test测试)", notes = "")
	@ApiImplicitParam(name = "id", value = "工单id", required = true, dataType = "Integer")
	@RequestMapping(value = "/testCreate.json", method = RequestMethod.POST)
	public String testCreate(@RequestBody SingleRequest<WorkOrderDO> request) {
		
		WorkOrderDO workOrder = request.getData();
		// 设置下一步任务：订单上摄控
		workOrder.setOrderID(workOrder.getOrderID());
		workOrder.setOrderNo("1535018459191793" + workOrder.getOrderID());
		workOrder.setOrderDetailID(workOrder.getOrderID());
		workOrder.setOrderProductSceenID(workOrder.getOrderID()); // order_detaill.screenId
		workOrder.setOrderProductSceenName("爱婴上门体验"); // order_detaill.name
		// TODO: 订单产品分类： 0新生儿照，1满月照；2婴儿照；3孕妈照
		workOrder.setOrderType(0); //
		// TODO: 订单产品分类： 10孕妈、12儿童、13新生儿、14婚纱、50全家福、51免费
		workOrder.setPackageCategory(0); // order_package.categoryId
		workOrder.setPackageName("爱婴上门体验套餐"); // order_package.name
		workOrder.setOrderPrice(new BigDecimal(7000)); // order.amout
		workOrder.setCustomID(10+workOrder.getOrderID()); // order.customerId
		workOrder.setCustomName("贾小宝"+workOrder.getOrderID()); // family_member
		workOrder.setTelephone("15922222222"); // family_member
		workOrder.setProvince("500000"); // contact
		workOrder.setCity("500100"); // contact
		workOrder.setDistrict("500103"); // contact
		workOrder.setAddress("解放碑街道解放碑地下环道重庆医科大学附属第二医院"); // contact

		workOrder.setPlanShotDate(new Date());// 计划拍摄时间 order_scene.shotDate
		workOrder.setShotHours(2); // 预计拍摄时长 order_scene.shotTime
		workOrder.setShotRatio(100); // 拍摄比例 order_scene.shotProportion
		workOrder.setShotSubject(""); // 拍摄主体 order.subject
		workOrder.setOrderStatus(0); // TODO：0-正常; 1-改期订单; 2-重拍订单; 3-补拍订单 ???
		workOrder.setFlag(0); //0普通、1特殊
		workOrder.setRemark(""); // TODO：订单备注
		workOrder.setEmployeeID(9);
		workOrder.setEmployeeName("test");
		
		SingleResponse<WorkOrderDO> response = new SingleResponse<WorkOrderDO>();
		ResultDO resultDO = workOrderService.createWorkOrder(workOrder);
		if (resultDO.isSuccess()) {
			response.setStatus(HttpStatus.SUCCESS.getErrorCode());
			response.setVersion(1);
			response.setMsg(HttpStatus.SUCCESS.getMsg());
			response.setData((WorkOrderDO) resultDO.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			// 查询失败
			response.setStatus(HttpStatus.SYSTEM_ERROR.getErrorCode());
			response.setVersion(1);
			response.setMsg(resultDO.getErrorMsg());
		}
		
		return encodeObject(response, PLANINTEXT);
	}

}
